package com.thinkgsp.jxc.service.impl;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import com.thinkgsp.jxc.model.Emp;
import com.thinkgsp.jxc.persistence.EmpMapper;
import com.thinkgsp.jxc.persistence.mybatis.QueryPagingHandler;
import com.thinkgsp.sys.model.NumberRoleConfig;
import com.thinkgsp.sys.model.SysAccountPeriod;
import com.thinkgsp.sys.model.SysUser;
import com.thinkgsp.sys.persistence.SysAccountPeriodMapper;
import com.thinkgsp.sys.service.NumberRoleService;

/**
 * 所有业务类的基类
 * @author evan
 *
 */
public abstract class GeneralServiceImpl {

	protected Log log = LogFactory.getLog(GeneralServiceImpl.class);
	
	@Autowired
	protected SysAccountPeriodMapper periodMapper;
	@Autowired
	protected EmpMapper empMapper;
	@Autowired
	protected Configuration configuration;
	@Autowired
	protected NumberRoleService numberRoleService;
	@Autowired
	protected NumberRoleConfig numberRoleConfig;
	@Autowired
	protected QueryPagingHandler queryPagingHandler;
	
	
	/**
	 * 设置会计期间持久化类,本方法用于测试目的
	 * @param periodMapper
	 */
	public void setPeriodMapper(SysAccountPeriodMapper periodMapper) {
		this.periodMapper = periodMapper;
	}
	
	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}
	
	public Emp getCurrentEmp() {
		SysUser user = getCurrentUser();
		Emp emp = empMapper.getEmp(user.getEmpId());
		return emp;
	}
	
	/**
	 * 获取当前登录的用户
	 * @return
	 */
	public SysUser getCurrentUser() throws AccessDeniedException {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		SysUser currentUser = null;
        if (auth.getPrincipal() instanceof UserDetails) {
            currentUser = (SysUser) auth.getPrincipal();
        } else if (auth.getDetails() instanceof UserDetails) {
            currentUser = (SysUser) auth.getDetails();
        } else {
            throw new AccessDeniedException("您未登陆系统。");
        }
        return currentUser;
	}
	
	/**
	 * 获取当前工作期间
	 * @return
	 */
	public SysAccountPeriod getCurrentPeriod() {
		return periodMapper.getCurrentPeriod();
	}
	
	public SysAccountPeriod getPeriod(int year,int period) {
		return periodMapper.getPeriod(year, period);
	}
}
